package com.scs.application.modules.upms.security.integration.authenticator;

import com.scs.application.core.utils.Md5Utils;
import com.scs.application.modules.upms.service.UserService;
import com.scs.application.modules.upms.vo.UserVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description: 手机短信验证登陆，通过手机号进行授权
 **/
@AllArgsConstructor
public class MobileAuthenticator extends AbstractPreparableIntegrationAuthenticator {

    @Autowired
    private UserService userService;

    public static final String OAUTH_TYPE = "mobile";

    @Override
    public UserVO authenticate(IntegrationAuthentication authentication) {
        UserVO infoVO = userService.findInfoByMobile(authentication.getUsername());

        if (infoVO != null) {
            /**
             * 访问 oauth/token时，password参数的值为 openid，所以此处得对openid进行加密，否则比对时会报错,
             * {@link org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks(UserDetails, UsernamePasswordAuthenticationToken)}
             */
            infoVO.setPassword(Md5Utils.md5(authentication.getUsername()));
        }

        return infoVO;
    }

    @Override
    public void prepare(IntegrationAuthentication authentication) {
    }

    @Override
    public boolean support(IntegrationAuthentication authentication) {
        return OAUTH_TYPE.equalsIgnoreCase(authentication.getAuthType());
    }
}
